{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Goodies of the [Python Standard Library](https://docs.python.org/3/library/#the-python-standard-library)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## [`json`](https://docs.python.org/3/library/json.html#module-json) for encoding and decoding JSON\n",
    "Because the web is filled with JSON nowadays and the good days of xml are gone."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = {'b': True, 'a': 1, 'nested': {'foo': 'bar'}, 'c': None, 'some_list': [1, 2, 3]}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Encoding"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "json_data = json.dumps(data)\n",
    "print('type: {} data: {}'.format(type(json_data), json_data))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Decoding"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "decoded = json.loads(json_data)\n",
    "print('type: {} data: {}'.format(type(decoded), decoded))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## [`unittest.mock`](https://docs.python.org/3/library/unittest.mock.html#module-unittest.mock)\n",
    "Although `pytest` is the preferred testing framework, `unittest.mock` module offers some goodies that are helpful also in pytest test cases. Mocking and patching are generally useful for \"faking\" some parts of the logic/state of the software under test. Common use cases are, for example, patching parts of code that interact with 3rd parties (e.g. some web services)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### [`MagicMock`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.MagicMock)\n",
    "\n",
    "In general, [Mocks](https://en.wikipedia.org/wiki/Mock_object) are simulated objects that replace the functionality/state of a real world object in a controlled way. Thus, they are especially useful in tests for mimicing some behavior of a specific part of the implementation under test.\n",
    "\n",
    "There is also a [`Mock`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock) class in the Python Standard Library but you usually want to use [`MagicMock`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.MagicMock) which is a subclass of `Mock`. `MagicMock` provides default implementation for the most of the magic methods (e.g. `__setitem__()` and `__getitem__()`)\n",
    "\n",
    "A potential use case could be something like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "class Client:\n",
    "    def __init__(self, url, username, password):\n",
    "        self.url = url\n",
    "        self.creds = (username, password)\n",
    "        \n",
    "    def fetch_some_data(self):\n",
    "        print('Here we could for example fetch data from 3rd party API and return the data.')\n",
    "        print('Now we will just return some random number between 1-100.')\n",
    "        return random.randint(1, 100)\n",
    "\n",
    "\n",
    "class MyApplication:\n",
    "    def __init__(self):\n",
    "        self.client = Client(url='https://somewhere/api', username='John Doe', password='secret123?')\n",
    "        \n",
    "    def do_something_fancy(self):\n",
    "        data = self.client.fetch_some_data()\n",
    "        return data**(1/2) # let's return a square root just for example\n",
    "    \n",
    "    \n",
    "####################\n",
    "# In the test module:\n",
    "\n",
    "from unittest.mock import MagicMock\n",
    "\n",
    "# Inside a test case:\n",
    "app = MyApplication()\n",
    "app.client = MagicMock() # Mock the client\n",
    "app.client.fetch_some_data.return_value = 4  # Set controlled behaviour\n",
    "result = app.do_something_fancy()\n",
    "assert result == 2\n",
    "print('All good, woop woop!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### [`patch`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch)\n",
    "The use cases of [`patch`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch) are pretty similar to `MacigMock`. The biggest difference is that `patch` is used as a context manager or a decorator. Object to be patched is given as an argument for `patch`. In addition, you can provide additional object as a second argument (`new`) which will replace the original one. In case the `new` is omitted, `MagicMock` will be used by default.\n",
    "\n",
    "Let's see how the example above would look like with `patch`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# In the test module:\n",
    "\n",
    "from unittest.mock import patch\n",
    "\n",
    "# Inside a test case:\n",
    "app = MyApplication()\n",
    "with patch('__main__.app.client') as patched_client:  # Patch the client \n",
    "    patched_client.fetch_some_data.return_value = 4 # Set controlled behaviour\n",
    "    result = app.do_something_fancy()\n",
    "    assert result == 2\n",
    "    print('All good, woop woop!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same but with a function decorator instead of a context manager. Note that here we are patching the whole `Client` class, not just the `client` instance variable of `app`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from unittest.mock import patch\n",
    "\n",
    "@patch('__main__.Client') # Patch the Client\n",
    "def test_do_something_fancy(client_cls):\n",
    "    client_cls().fetch_some_data.return_value = 4 # Set controlled behaviour\n",
    "    app = MyApplication()\n",
    "    result = app.do_something_fancy()\n",
    "    assert result == 2\n",
    "    print('All good, woop woop!')\n",
    "    \n",
    "    \n",
    "test_do_something_fancy()  # This is just for the sake of example"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## [`collections`](https://docs.python.org/3/library/collections.html#module-collections)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### [`namedtuple`](https://docs.python.org/3/library/collections.html#collections.namedtuple)\n",
    "A great helper for creating more readable and self documenting code.\n",
    "\n",
    "`namedtuple` is a function that returns a tuple whose fields have names and also the tuple itself has a name (just like classes and their instance variables). Potential use cases include storing data which should be immutable. If you can use Python 3.7 or newer, you may want to take a look at [`dataclasses`](https://docs.python.org/3/library/dataclasses.html#module-dataclasses) as well. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import namedtuple\n",
    "\n",
    "Person = namedtuple('Person', ['name', 'age', 'is_gangster'])\n",
    "\n",
    "# instance creation is similar to classes\n",
    "john = Person('John Doe', 83, True)\n",
    "lisa = Person('Lis Doe', age=77, is_gangster=False)\n",
    "\n",
    "print(john, lisa)\n",
    "print('Is John a gangster: {}'.format(john.is_gangster))\n",
    "\n",
    "# tuples are immutable, thus you can't do this\n",
    "#john.is_gangster = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter)\n",
    "For counting the occurences of elements in a collection."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import Counter\n",
    "\n",
    "data = [1, 2, 3, 1, 2, 4, 5, 6, 2]\n",
    "\n",
    "counter = Counter(data)\n",
    "print('type: {}, counter: {}'.format(type(counter), counter))\n",
    "\n",
    "print('count of twos: {}'.format(counter[2]))\n",
    "print('count of tens: {}'.format(counter[10])) # zero for non existing\n",
    "\n",
    "print('counter is a dict: {}'.format(isinstance(counter, dict)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict)\n",
    "For cleaner code for populating dictionaries.\n",
    "\n",
    "Let's first see how you could use a normal `dict`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = (1, 2, 3, 4, 3, 2, 5, 6, 7)\n",
    "\n",
    "my_dict = {}\n",
    "for val in data:\n",
    "    if val % 2:\n",
    "        if not 'odd' in my_dict:\n",
    "            my_dict['odd'] = []\n",
    "        my_dict['odd'].append(val)\n",
    "    else:\n",
    "        if not 'even' in my_dict:\n",
    "            my_dict['even'] = []\n",
    "        my_dict['even'].append(val)\n",
    "        \n",
    "print(my_dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `defaultdict`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "my_dict = defaultdict(list)\n",
    "for val in data:\n",
    "    if val % 2:\n",
    "        my_dict['odd'].append(val)\n",
    "    else:\n",
    "        my_dict['even'].append(val)\n",
    "print(my_dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the above example, `defaultdict` makes sure that a fresh `list` is automatically initialized as a value when a new key is added.\n",
    "\n",
    "Here's another example with `int` as a default."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "my_dict = defaultdict(int)\n",
    "for val in data:\n",
    "    if val % 2:\n",
    "        my_dict['odd_count'] += 1\n",
    "    else:\n",
    "        my_dict['even_count'] += 1\n",
    "print(my_dict)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
